package com.hnkywl.sts.service.sys;

import com.hnkywl.sts.dao.sys.GwDao;
import com.hnkywl.sts.entity.sys.Gw;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.sts.service.sys
 * 类描述:    岗位服务类
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Service
public class GwService {
    private GwDao gwDao;

    /**
     * 查询岗位列表
     * @param gwmc     岗位名称
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findAllGw(String gwmc, int pageNo, int pageSize) {
        Page<Gw> gwPage = this.gwDao.findGwList(gwmc, pageNo, pageSize);
        List<Gw> gwList = gwPage.getResult() == null ? new ArrayList<Gw>() : gwPage.getResult();
        Map<String,Object> otherParam = new HashMap<String,Object>();
        otherParam.put("list_jsList","mc");
        String gwJson = BaseUtils.fetchCollectionToJson(gwList,otherParam, "id","mc","jsList", "rzyq","ms","pxh");
        return "{\"total\":" + gwPage.getTotalCount() + ",\"rows\":[" + gwJson + "]}";
    }

    /**
     *查询岗位名称列表
     * @return
     */
    public String findGwMc() {
        String gwJson = BaseUtils.fetchCollectionToJson(gwDao.findAll(), "id","mc","ms");
        return "{\"total\":" + gwDao.findAll().size() + ",\"rows\":[" + gwJson + "]}";
    }

    /**
     * 查询岗位明细
     * @param id 岗位id
     * @return
     */
    @Transactional
    public Gw findGwDetail(Long id) {
        return this.gwDao.get(id);
    }

    /**
     * 保存岗位信息
     * @param gw 岗位实体
     * @return
     */
    @Transactional
    public void saveGw(Gw gw) throws RuntimeException {
        gw.setDateCreated(new Date());
        gw.setLastUpdated(gw.getDateCreated());
        this.gwDao.save(gw);
    }

    /**
     * 删除岗位信息
     * @param id 岗位id
     * @return
     */
    @Transactional
    public void deleteGw(Long id) {
        Gw gw=gwDao.get(id);
        if (!gw.getYgList().isEmpty()) {
            throw new RuntimeException("此岗位已被使用，不能删除！");
        }
        gw.setLastUpdated(new Date());
        gw.setDeleted(1);
        this.gwDao.save(gw);
    }

    /**
     * 获取岗位排序号
     * @return
     */
    public Integer findNextPxh() {
        return this.gwDao.findMaxPxh() == null ? 1 : this.gwDao.findMaxPxh()+1;
    }

    /**
     * ajax远程验证
     * @param value 验证值
     * @param field 验证字段
     * @return
     */
    public boolean ajaxValidate(Long id,String value, String field) {
        return gwDao.checkUnique(id,value,field);
    }

    @Autowired
    public void setGwDao(GwDao gwDao) {
        this.gwDao = gwDao;
    }
}
